package com.lambkit.core.flow;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.NoResourceException;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.nio.charset.Charset;

/**
 * @author yangyong(孤竹行)
 */
public class FlowInstanceJsonBuilder implements IFlowInstanceBuilder {

    private FlowInstanceObject flowInstanceObject;
    private String jsonFile;

    public FlowInstanceJsonBuilder(String instanceFile, String flowFile) {
        this.jsonFile = instanceFile;
        FlowObject flowObject = readFlowObjectFromFile(flowFile);
        readFlowInstanceObject(flowObject);
    }

    public FlowInstanceJsonBuilder(String jsonFile, FlowObject flowObject) {
        this.jsonFile = jsonFile;
        readFlowInstanceObject(flowObject);
    }


    private FlowObject readFlowObjectFromFile(String flowFile) {
        String json = ResourceUtil.readUtf8Str(flowFile);
        return readFlowObjectFromJson(json);
    }

    private FlowObject readFlowObjectFromJson(String json) {
        FlowObject flowObject = null;
        if(StrUtil.isNotBlank(json)) {
            JSONObject jsonFlow = JSONUtil.parseObj(json);
            flowObject = jsonFlow.toBean(FlowObject.class);
        } else {
            flowObject = new FlowObject();
            flowObject.setCode(IdUtil.simpleUUID());
        }
        return flowObject;
    }

    private void readFlowInstanceObject(FlowObject flowObject) {
        String json = null;
        try {
            json = ResourceUtil.readUtf8Str(jsonFile);
        } catch (NoResourceException e) {
            // ignore
        }
        if(StrUtil.isNotBlank(json)) {
            JSONObject jsonFlow = JSONUtil.parseObj(json);
            this.flowInstanceObject = jsonFlow.toBean(FlowInstanceObject.class);
        } else {
            this.flowInstanceObject = new FlowInstanceObject();
            this.flowInstanceObject.setFlow(flowObject);
            this.flowInstanceObject.setCode(IdUtil.simpleUUID());
            this.flowInstanceObject.setTitle(flowObject.getTitle());
        }
    }

    @Override
    public FlowInstanceObject getInstance() {
        return flowInstanceObject;
    }

    @Override
    public void saveInstance() {
        if (flowInstanceObject != null) {
            File file = new File(jsonFile);
            String json = JSONUtil.toJsonPrettyStr(flowInstanceObject);
            FileUtil.writeString(json, file, Charset.forName("UTF-8"));
        }
    }

}
